import { UIHelper } from "../game/util/UIHelper";
import ComponentBase from "./ComponentBase";
import { Logger } from "./Logger";
import UIManager from "./UIManager";
import { UI_Cache_Type, UI_Config } from "./UI_Config";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ViewBase extends ComponentBase {

    @property()
    private canBgClose: boolean = true;

    @property()
    private needDark: boolean = true;

    public onlyId: number;

    public uiConfig: UI_Config;
    public isOpen: boolean;

    public onInitBase(uiConfig: UI_Config, ...optionalParams: any[]) {
        this.isOpen = true;
        this.uiConfig = uiConfig;

        let canBgCloseNode: cc.Node = this.node.getChildByName("canBgCloseNode");
        // Logger.log("onInitBase==", uiConfig)
        if (!canBgCloseNode && this.needDark) {
            canBgCloseNode = cc.instantiate(UIManager.instance.darkLayer)
            canBgCloseNode.name = "canBgCloseNode"
            canBgCloseNode.parent = this.node
            canBgCloseNode.zIndex = -1;
            canBgCloseNode.active = true;
            let bgWidget: cc.Widget = canBgCloseNode.getComponent(cc.Widget);
            bgWidget.top = 0;
            bgWidget.bottom = 0
            bgWidget.left = 0;
            bgWidget.right = 0;
            canBgCloseNode.width = cc.winSize.width
            canBgCloseNode.height = cc.winSize.height
        }
        if(canBgCloseNode){
            if (this.canBgClose) {
                UIHelper.onAddEvent(canBgCloseNode, () => {
                    this.closeView();
                }, cc.Button.Transition.NONE)
            }else{
                UIHelper.onAddEvent(canBgCloseNode, () => {
                }, cc.Button.Transition.NONE)
            }
        }
        let btnClose: cc.Node = this.node.getChildByName("btnClose")
        if (btnClose) {
            UIHelper.onAddEvent(btnClose, () => {
                this.closeView();
            })
        }
        let btnOK:cc.Node = this.node.getChildByName("btnOK")
        if(btnOK){
            UIHelper.onAddEvent(btnOK, () => {
                this.closeView();
            })
        }
        this.onInitChild(...optionalParams);
    }

    public onInitChild(...optionalParams: any[]) {

    }

    /** 设置为顶层UI */
    protected setTopUI() {
        UIManager.instance.setTopUI(this);
    }

    public closeView(forceRelease: boolean = false) {
        if (this.isOpen) {
            this.isOpen = false;
            Logger.log("closeView", this.uiConfig)
            if (this.uiConfig.isSingle && this.uiConfig.cacheType != UI_Cache_Type.noCache) {
                this.node.active = false;
            } else {
                this.node.destroy();
            }
            UIManager.instance.closeView(this)
            if (forceRelease) {
                UIManager.instance.releaseForce(this)
            }

        }
    }
}
